package handler

import (
	"fan-ctrl-sys/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func CreateMovie(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	score := c.PostForm("score")
	img := c.PostForm("img")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	data := model.Movie{
		Title:   title,
		Content: content,
		Img:     img,
		Score:   score,
		UserID:  userId,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})

}

func ListMovie(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	size, _ := strconv.Atoi(c.DefaultPostForm("size", "3"))

	offset := (page - 1) * size
	var count int64
	var movie []model.Movie
	err := model.DB.Model(&model.Movie{}).Count(&count).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取条数不正确",
		})
		return
	}
	err = model.DB.Offset(offset).Limit(size).Find(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取数据失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取数据成功",
		"data": gin.H{
			"movie": movie,
			"count": count,
		},
	})
	return
}

func DetailMovie(c *gin.Context) {
	id := c.Query("id")
	var movie model.Movie
	err := model.DB.Where("id=?", id).Order("view_count desc").First(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": movie,
	})

}
